from flask import Flask, session, g
import config
from extension import db, migrate, email, ma
from router.auth import bp as auth_bp
from router.qa import bp as qa_bp
from router.answer import bp as answer_bp
from flask_cors import CORS
from models.auth import UserModel, EmailCaptchaModel
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)

email.init_app(app)

migrate.init_app(app, db)

ma.init_app(app)

CORS(app, origins=["http://127.0.0.1:5173"], supports_credentials=True)

app.register_blueprint(auth_bp)
app.register_blueprint(qa_bp)
app.register_blueprint(answer_bp)

@app.before_request
def before_request():
    user_id = session.get('user_id')
    if user_id:
        user = UserModel.query.filter_by(id=user_id).first()
        setattr(g, 'user', user)
    else:
        setattr(g, 'user', None)

@app.context_processor
def context_processor():
    return {
        'user': g.user
    }


if __name__ == '__main__':
    app.run()
